﻿
// XXXPLCDlg.cpp : implementation file
//

#include "stdafx.h"
#include "XXXPLC.h"
#include "XXXPLCDlg.h"
#include "afxdialogex.h"
#include <atlconv.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define  WM_THREAD_STOP (WM_USER+1)

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
	static TCHAR szBuffer[90];
	static TCHAR szTemp[80];

	static TCHAR szFormat[] = _T("%08lX: %s");
	HWND hwndListBox = (HWND)lParam;
	CListBox* plb = (CListBox*)CWnd::FromHandle(hwndListBox);

	GetWindowText(hwnd, szTemp, sizeof(szTemp));
	_stprintf_s(szBuffer, 90, szFormat, hwnd, szTemp);

	return (plb->AddString(szBuffer) >= 0) ? TRUE : FALSE;
}

 std::string WStringToString(const std::wstring &wstr)
 {
      std::string str(wstr.length(), ' ');
      std::copy(wstr.begin(), wstr.end(), str.begin());
      return str; 
 }

DWORD WINAPI ThreadProc(LPVOID pParam)
{
	/*CXXXPLCDlg *dlg = (CXXXPLCDlg*)pParam;
	dlg->OnWork();
	dlg->prepare();
	return 0;
*/
	while(true) 
	{
		MSG msg; 
		while(PeekMessage(&msg,NULL,0,0,PM_REMOVE)){ //将消息队列里的消息逐个读入msg
			if(msg.message==WM_THREAD_STOP){ //如果收到终止消息则退出
				//TODO：放在堆里的变量要在这里手动清理
				((CXXXPLCDlg*)pParam)->prepare();
				return 0; //线程正常返回，会释放局部变量等内存资源
			}
			else{
				
				DispatchMessage(&msg);//字面意思，不解释
			}
		}
		//work
		CXXXPLCDlg *dlg = (CXXXPLCDlg*)pParam;
		if (dlg->OnWork())
		{
			break;
		}
	}

	((CXXXPLCDlg*)pParam)->prepare();

	return 0;
}
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CXXXPLCDlg dialog




CXXXPLCDlg::CXXXPLCDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CXXXPLCDlg::IDD, pParent)
	, m_name(_T("")),m_counter(NULL)
	, m_csType(_T(""))
	, m_csWidth(_T(""))
	, m_isWorking(false)
	, m_start(_T(""))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CXXXPLCDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO_TYPE, m_ctrlType);
	DDX_Control(pDX, IDC_COMBO_WIDTH, m_ctrlWidth);
	DDX_Control(pDX, IDC_LIST1, m_listBox);
	DDX_Text(pDX, IDC_EDIT_NAME, m_name);
	DDX_CBString(pDX, IDC_COMBO_TYPE, m_csType);
	DDX_CBString(pDX, IDC_COMBO_WIDTH, m_csWidth);
	DDX_Text(pDX, IDC_EDIT_START, m_start);
	DDX_Text(pDX, IDC_EDIT_WAITTIME, m_waitTime);
}

BEGIN_MESSAGE_MAP(CXXXPLCDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_START, &CXXXPLCDlg::OnBnClickedBtnStart)
	ON_BN_CLICKED(IDC_BTN_CLEAR, &CXXXPLCDlg::OnBnClickedBtnClear)
END_MESSAGE_MAP()


// CXXXPLCDlg message handlers

BOOL CXXXPLCDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	m_ctrlType.AddString(_T("Number"));
	m_ctrlType.AddString(_T("Alphabet Lower Case"));
	m_ctrlType.AddString(_T("Alphabet Upper Case"));
	m_ctrlType.AddString(_T("Alphabet Lower&Upper Case"));
	m_ctrlType.AddString(_T("Alphanumber Lower Case"));
	m_ctrlType.AddString(_T("Alphanumber Upper Case"));
	m_ctrlType.AddString(_T("Alphanumber Lower&Upper Case"));

	initValue();


	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CXXXPLCDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CXXXPLCDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CXXXPLCDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CXXXPLCDlg::OnBnClickedBtnStart()
{
	// TODO: Add your control notification handler code here
	if (!m_isWorking)//Running
	{
		UpdateData();

		if (m_name.IsEmpty())
		{
			MessageBox(_T("Window Name is empty!"), _T("Error"));
			return;
		}

		if (m_waitTime < 50)
		{
			MessageBox(_T("Wait time must be greater than 50 ms."), _T("Error"));
			return;
		}

		//UpdateData(FALSE);
		int nIdx = m_ctrlType.GetCurSel();
		COUNTER_TYPE type = (COUNTER_TYPE) nIdx;
		int width = _wtoi(m_csWidth.GetBuffer());

		if (!m_counter){
			std::wstring wStart(m_start.GetBuffer());
			std::string strStart = WStringToString(wStart);
			m_counter = new CCounter(type, width, strStart);
			m_counter->Validate();
		}

		//MessageBox(m_csType);

		m_thread = AfxBeginThread((AFX_THREADPROC)ThreadProc,this);
		if(m_thread) {
				m_isWorking= true;
				SetDlgItemText(IDC_BTN_START,_T("Stop"));
		}

	}
	else//Not started
	{
		::PostThreadMessage(m_thread->m_nThreadID, WM_THREAD_STOP,0, 0);
	}
	
}

HWND CXXXPLCDlg::FindErrorWindow()
{
	HWND hWndFound = 0;


	return 0;
}

BOOL CXXXPLCDlg::OnWork()
{
	int count = m_listBox.GetCount();
	for(int i = 0 ; i < count; ++i)
	{
		m_listBox.DeleteString(0);
	}

	HWND hWndDlg = ::FindWindow(NULL, _T("设置访问权限"));
	if (!hWndDlg) {
		m_listBox.AddString(_T("Can't find the window 设置访问权限"));
		Sleep(5000);
		return FALSE;
	}

	//::SetForegroundWindow(hWndDlg);
	//密码框
	HWND hWndEdit = ::FindWindowEx(hWndDlg, 0,_T("Edit"),_T(""));
	
	CString tryPwd(m_counter->Value().c_str());
	m_counter->Tick();

	//填充密码
	::SendMessage(hWndEdit,WM_SETTEXT,tryPwd.GetLength(), (LPARAM)tryPwd.GetBuffer());
	CString str;
	str.Format(_T("Set password %s"),tryPwd);
	m_listBox.AddString(str);

	//单击确定
	HWND hWndOK = ::FindWindowEx(hWndDlg, 0 ,_T("Button"),_T("确定"));
	if(!hWndOK) {
		m_listBox.AddString(_T("Can't find 确定 button"));
		return FALSE;
	}
	m_listBox.AddString(_T("Clicking 确定 button"));
	/////
	::PostMessage(hWndOK, BM_CLICK,0,0);
	m_listBox.AddString(_T("Click 确定 button"));

	Sleep(m_waitTime);
	//弹出密码测
	m_listBox.AddString(_T("Finding LAD/STL/FBD window"));
	HWND hWndResult = ::FindWindow(NULL,m_name);
	

	if(!hWndResult) {
		str.Format(_T("Window %s NOT Found. Successfully?"),m_name);
		m_listBox.AddString(str);
		return TRUE;
	}
	//::SetForegroundWindow(hWndResult);

	str.Format(_T("Found Window %s"),m_name);
	m_listBox.AddString(str);
	
		HWND hWndMsg = ::FindWindowEx(hWndResult,0, _T("Static"),NULL);
		TCHAR szMsg[100] ={0};
		::GetWindowText(hWndMsg,szMsg,100);

		CString csMsg(szMsg);

		str.Format(_T("Error msg %s"),csMsg);
			m_listBox.AddString(str);

		if (csMsg.Compare(_T("密码输入错误。")) == 0)
		{
			HWND hWndBtnClose = ::FindWindowEx(hWndResult, 0, _T("Button"), _T("确定"));

			if (hWndBtnClose) ::PostMessage(hWndBtnClose, BM_CLICK,0,0);
			str.Format(_T("Password %s Failed"),tryPwd);
			m_listBox.AddString(str);
		}
		else 
		{
			str.Format(_T("Password Found %s"),tryPwd);
			m_listBox.AddString(str);
			return TRUE;
		}
	//}
		Sleep(10);

	return FALSE;
}


void CXXXPLCDlg::OnBnClickedBtnClear()
{
	// TODO: 在此添加控件通知处理程序代码
	int count = m_listBox.GetCount();
	for(int i = 0 ; i < count; ++i)
	{
		m_listBox.DeleteString(0);
	}

	initValue();

	if (m_counter){
		delete m_counter;
		m_counter = NULL;
	}
}

void CXXXPLCDlg::prepare()
{
	m_isWorking = false;
	SetDlgItemText(IDC_BTN_START,_T("Start"));
}

void CXXXPLCDlg::initValue()
{
	m_name = _T("LAD/STL/FBD  (33:281)");
	m_waitTime = 80;

	m_start = "00000000";

	UpdateData(FALSE);
	m_ctrlType.SetCurSel(0);
	m_ctrlWidth.SetCurSel(7); //8
}
